import {
	pageRouter,
	apiRouter
} from './Routers';
import Conf from '../conf';
import path from 'path';
import fs from 'fs';

const debug = require('debug')('ebook:routes:index');

export default function routes(router){
	pageRouter(router);
	apiRouter(router);
	// 404
	['get','post','put','del'].forEach((m)=>{
		router[m]('*',async (cx,next)=>{
			// await next();
			let dirname = cx.path.match(/^\/([^/]+)/);
			if (dirname) {
				dirname = dirname[1];
				let hasBook = await cx.locServe.books.find({dirname});
				if (hasBook.length) {
					let defIndex = cx.path.replace(hasBook[0].isMdpage === '1'?(/^(\/.+?\/[^/]+).*/i):(/^(\/[^/]+).*/i),'$1/');
					let defPath = path.join(process.cwd(),Conf.upload.uploadedDir,defIndex);
					let existsDefIndex = fs.existsSync(defPath);
					cx.response.redirect(existsDefIndex?defIndex:'/404.html');
					return;
				}
			}
			cx.response.redirect('/404.html');
		});
	});
	return router.routes();
}

